use proc_macro::TokenStream;
use quote::quote;
use syn::{DeriveInput, parse_macro_input};

/// Component trait的派生宏，用于自动实现Component trait的as_any和as_any_mut方法
/// 该宏已在tvk_render_core::ecs::components::Component trait中导出，只需引入前者即可，或两者路径都引入
#[proc_macro_derive(Component)]
pub fn derive_component(input: TokenStream) -> TokenStream {
    // 解析输入的TokenStream为DeriveInput结构体
    let input = parse_macro_input!(input as DeriveInput);

    // 获取结构体的名称
    let name = &input.ident;

    // 生成实现Component trait的代码
    let expanded = quote! {
        // 为结构体自动实现Component trait
        impl Component for #name {
            fn as_any(&self) -> &dyn std::any::Any {
                self
            }

            fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
                self
            }

            fn clone_box(&self) -> Box<dyn Component> {
                Box::new(self.clone())
            }
        }
    };

    // 将生成的代码转换回TokenStream并返回
    TokenStream::from(expanded)
}
